//
//  MeetingViewController.m
//  RongRTCMeeting
//
//  Created by LiuLinhong on 2017/08/09.
//  Copyright © 2017年 Beijing Rongcloud Network Technology Co. , Ltd. All rights reserved.
//

#import "MeetingViewController.h"
#import "MeetingWindowController.h"
#import "AppDelegate.h"
#import "CommonUtility.h"
#import "LogonWindowController.h"
#import "LogonViewController.h"
#import <RongRTCLib/RongRTCEngine.h>
#import <AppKit/NSOpenGLView.h>
#import "LeftMVControlCollectionViewItem.h"

@interface MeetingViewController ()
{
    NSInteger frameRateIndex, codeRateIndex, connectionStyleIndex, codingStyleIndex, minCodeRateIndex;
    NSTextField *messageAlertTextField;
    MessageAlertBlock messageAlertBlock;
    NSTimer *breathTimer, *endBreathTimer;
    ApplyRequestBlock applyRequestBlock;
    NSImage *signalImageDis, *signalImage0, *signalImage1, *signalImage2, *signalImage3, *signalImage4, *signalImage5;
    NSInteger videoSizeSelectedIndex;
    CGFloat localVideoWidth, localVideoHeight;
    NSInteger callingBreathLevel;
    BOOL isJoinedChannel, isAudioOnly, isGPUFilter, isSRTPEncrypt;
    NSUInteger chatResolutionRatioIndex;
}

@end

@implementation MeetingViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    LarkMeetingManager.isSwitchVideoView = NO;
    LarkMeetingManager.isCloseCamera = NO;
    LarkMeetingManager.is0RequestSpeak = NO;
    LarkMeetingManager.is1Invite = NO;
    LarkMeetingManager.is2ManageMeeting = NO;
    LarkMeetingManager.is3UseWhiteBoard = NO;
    LarkMeetingManager.is4ShareScreen = NO;
    LarkMeetingManager.is5Speaker = NO;
    LarkMeetingManager.is7Mute = NO;
    LarkMeetingManager.isCallingBreath = NO;
    LarkMeetingManager.selectedSwitchCellIndex = -1;
    LarkMeetingManager.isWhiteBoardExist = NO;
    LarkMeetingManager.isFullScreen = NO;
    LarkMeetingManager.isDataInfoOpen = NO;
    isJoinedChannel = NO;
    videoSizeSelectedIndex = -1;
    
    signalImageDis = [NSImage imageNamed:@"MeetingSignalDisconnected"];
    signalImage0 = [NSImage imageNamed:@"MeetingSignal0"];
    signalImage1 = [NSImage imageNamed:@"MeetingSignal1"];
    signalImage2 = [NSImage imageNamed:@"MeetingSignal2"];
    signalImage3 = [NSImage imageNamed:@"MeetingSignal3"];
    signalImage4 = [NSImage imageNamed:@"MeetingSignal4"];
    signalImage5 = [NSImage imageNamed:@"MeetingSignal5"];
    
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(meetingWindowClosed) name:@"meetingWindowClosed" object:nil];
}

- (void)viewWillAppear
{
    [super viewWillAppear];
    
    if (!isJoinedChannel)
    {
        DLog(@"LLH..... channelID: %@", self.channelID);
        isJoinedChannel = YES;
        self.view.window.title = self.channelID;
        self.meetingWindowDelegateImpl = [[MeetingWindowDelegateImpl alloc] initWithViewController:self];
        self.view.window.delegate = self.meetingWindowDelegateImpl;
        
        self.meetingSwitchPageViewDelegateSource = [[MeetingSwitchPageViewDelegateSource alloc] initWithViewController:self];
        self.leftMVControlCollectionViewDelegateSource = [[LeftMVControlCollectionViewDelegateSource alloc] initWithViewController:self];
        self.rightMVTableViewDelegateSource = [[RightMVTableViewDelegateSource alloc] initWithViewController:self];
        self.whiteBoardWebUIDelegateImpl = [[WhiteBoardWebUIDelegateImpl alloc] initWithViewController:self];
        self.avDataInfoTableViewDelegateSource = [[AVDataInfoTableViewDelegateSource alloc] initWithViewController:self];
        self.meetingViewBuilder = [[MeetingViewBuilder alloc] initWithViewController:self];
        
        self.meetingRongRTCEngineDelegateImpl = [[MeetingRongRTCEngineDelegateImpl alloc] initWithViewController:self];
        self.rongRTCEngine = [RongRTCEngine sharedRongRTCEngine];
        self.rongRTCEngine.isSendLostReport = YES;
        [self.rongRTCEngine setDelegate:self.meetingRongRTCEngineDelegateImpl];
        [self joinChannel];
        [self reminderUserDeviceStatus];
//        [self rightMemberButtonPressed];
    }
}

#pragma mark - init UserDefaults data
- (void)initUserDefaultsData
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES);
    NSString *docDir = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
    NSString *settingUserDefaultPath = [docDir stringByAppendingPathComponent:File_SettingUserDefaults_Plist];
    DLog(@"LLH...... settingUserDefaultPath: %@", settingUserDefaultPath);
    BOOL isPlistExist = [CommonUtility isFileExistsAtPath:settingUserDefaultPath];
    
    if (isPlistExist)
    {
        NSUserDefaults *settingUserDefaults = [LogonViewController shareSettingUserDefaults];
        isAudioOnly = [[settingUserDefaults valueForKey:Key_AudioOnly] boolValue];
        chatResolutionRatioIndex = [[settingUserDefaults valueForKey:Key_ResolutionRatio] integerValue];
        frameRateIndex = [[settingUserDefaults valueForKey:Key_FrameRate] integerValue];
        codeRateIndex = [[settingUserDefaults valueForKey:Key_CodeRate] integerValue];
        connectionStyleIndex = [[settingUserDefaults valueForKey:Key_ConnectionStyle] integerValue];
        codingStyleIndex = [[settingUserDefaults valueForKey:Key_CodingStyle] integerValue];
        minCodeRateIndex = [[settingUserDefaults valueForKey:Key_CodeRateMin] integerValue];
        LarkMeetingManager.observerIndex = [[settingUserDefaults valueForKey:Key_Observer] integerValue];
        LarkMeetingManager.closeCameraIndex = [[settingUserDefaults valueForKey:Key_CloseCamera] integerValue];
        isGPUFilter = [[settingUserDefaults valueForKey:Key_GPUFilter] boolValue];
        isSRTPEncrypt = [[settingUserDefaults valueForKey:Key_SRTPEncrypt] boolValue];
    }
    else
    {
        isAudioOnly = Value_Default_AudioOnly;
        chatResolutionRatioIndex = Value_Default_ResolutionRatio;
        frameRateIndex = Value_Default_FrameRate;
        codeRateIndex = Value_Default_CodeRate;
        connectionStyleIndex = Value_Default_Connection_Style;
        codingStyleIndex = Value_Default_Coding_Style;
        minCodeRateIndex = Value_Default_MinCodeRate;
        LarkMeetingManager.observerIndex = Value_Default_Observer;
        LarkMeetingManager.closeCameraIndex = Value_Default_CloseCamera;
        isGPUFilter = Value_Default_GPUFilter;
        isSRTPEncrypt = Value_Default_SRTPEncrypt;
    }
}

- (void)configParameter
{
    if (isAudioOnly) {
        DLog(@"LLH...... 纯音频");}
    else {
        DLog(@"LLH...... 音频+视频");}
    
    NSInteger videoProfile = RongRTC_VideoProfile_Invalid;
    switch (chatResolutionRatioIndex)
    {
        case 0:
        {
            DLog(@"LLH...... 分辨率: 320x240");
            localVideoWidth = 240;
            localVideoHeight = 320;
            if (frameRateIndex == 0)
                videoProfile = RongRTC_VideoProfile_320_240P;
            else if (frameRateIndex == 1)
                videoProfile = RongRTC_VideoProfile_320_240P_1;
            else if (frameRateIndex == 2)
                videoProfile = RongRTC_VideoProfile_320_240P_2;
        }
            break;
        case 1:
        {
            DLog(@"LLH...... 分辨率: 640x480");
            localVideoWidth = 480;
            localVideoHeight = 640;
            if (frameRateIndex == 0)
                videoProfile = RongRTC_VideoProfile_640_480P;
            else if (frameRateIndex == 1)
                videoProfile = RongRTC_VideoProfile_640_480P_1;
            else if (frameRateIndex == 2)
                videoProfile = RongRTC_VideoProfile_640_480P_2;
        }
            break;
        case 2:
        {
            DLog(@"LLH...... 分辨率: 1280x720");
            localVideoWidth = 720;
            localVideoHeight = 1280;
            if (frameRateIndex == 0)
                videoProfile = RongRTC_VideoProfile_1280_720P;
            else if (frameRateIndex == 1)
                videoProfile = RongRTC_VideoProfile_1280_720P_1;
            else if (frameRateIndex == 2)
                videoProfile = RongRTC_VideoProfile_1280_720P_2;
        }
            break;
        default:
            break;
    }
    
    if (frameRateIndex == 0){
        DLog(@"LLH........ 帧率: 15");}
    else if (frameRateIndex == 1){
        DLog(@"LLH........ 帧率: 24");}
    else if (frameRateIndex == 2){
        DLog(@"LLH........ 帧率: 30");}
    
    NSArray *codeRateArray = [CommonUtility getPlistArrayByplistName:Key_CodeRate];
    NSDictionary *codeRateDictionary = codeRateArray[chatResolutionRatioIndex];
    //NSInteger min = [codeRateDictionary[Key_Min] integerValue];
    NSInteger max = [codeRateDictionary[Key_Max] integerValue];
    NSInteger step = [codeRateDictionary[Key_Step] integerValue];
    
    NSMutableArray *muArray = [NSMutableArray array];
    for (NSInteger temp = 0; temp <= max; temp += step)
        [muArray addObject:[NSString stringWithFormat:@"%zd", temp]];
    
    NSInteger maxCodeRate = -1;
    if ([muArray count] > codeRateIndex)
    {
        maxCodeRate = [muArray[codeRateIndex] integerValue];
        DLog(@"LLH........ 最大码率: %zd", maxCodeRate);
    }
    else
    {
        DLog(@"LLH...... 最大码率选项出现越界... 错误 codeRateIndex: %zd", codeRateIndex);
    }
    
    NSMutableArray *minArray = [NSMutableArray array];
    for (NSInteger tmp = 0; tmp <= max; tmp += step)
        [minArray addObject:[NSString stringWithFormat:@"%zd", tmp]];
    
    NSInteger minCodeRate = -1;
    if ([minArray count] > minCodeRateIndex)
    {
        minCodeRate = [minArray[minCodeRateIndex] integerValue];
        DLog(@"LLH........ 最小码率: %zd", minCodeRate);
    }
    else
    {
        DLog(@"LLH...... 最小码率选项出现越界... 错误 minCodeRateIndex: %zd", minCodeRateIndex);
    }
    
    NSInteger sessionType;
    if (connectionStyleIndex)
    {
        sessionType = 1;
        DLog(@"LLH......sessionType:%zd 连接方式: Relay", sessionType);
    }
    else
    {
        sessionType = 0;
        DLog(@"LLH......sessionType:%zd 连接方式: P2P", sessionType);
    }
    
    switch (LarkMeetingManager.closeCameraIndex)
    {
        case 0:
        {
            LarkMeetingManager.closeCameraIndex = RongRTC_User_Only_Audio;
            DLog(@"LLH......self.closeCameraIndex: %zd 关闭视频,仅音频", LarkMeetingManager.closeCameraIndex);
        }
            break;
        case 1:
        {
            LarkMeetingManager.closeCameraIndex = RongRTC_User_Audio_Video;
            DLog(@"LLH......self.closeCameraIndex: %zd 打开视频", LarkMeetingManager.closeCameraIndex);
        }
            break;
        default:
        {
            LarkMeetingManager.closeCameraIndex = RongRTC_User_Audio_Video;
            DLog(@"LLH......self.closeCameraIndex: %zd 打开视频", LarkMeetingManager.closeCameraIndex);
        }
            break;
    }
    
    switch (LarkMeetingManager.observerIndex)
    {
        case RongRTC_User_Normal:
            DLog(@"LLH......self.observerIndex:%zd 观察者方式: 正常,非观察者", LarkMeetingManager.observerIndex);
            break;
        case RongRTC_User_Observer:
            DLog(@"LLH......self.observerIndex:%zd 观察者方式: 观察者", LarkMeetingManager.observerIndex);
            break;
        default:
            break;
    }
    
    NSInteger codeType;
    switch (codingStyleIndex)
    {
        case 0:
        {
            codeType = 0;
            DLog(@"LLH......codeType:%zd 编码方式: kVideoTypeH264", codeType);
        }
            break;
        case 1:
        {
            codeType = 1;
            DLog(@"LLH......codeType:%zd 编码方式: kVideoTypeVP8", codeType);
        }
            break;
        case 2:
        {
            codeType = 2;
            DLog(@"LLH......codeType:%zd 编码方式: kVideoTypeVP9", codeType);
        }
            break;
        default:
        {
            codeType = 0;
            DLog(@"LLH......codeType:%zd 编码方式: kVideoTypeH264", codeType);
        }
            break;
    }
    
    self.paraDic = [NSMutableDictionary dictionary];
    self.paraDic[kAudioOnly] = @(isAudioOnly);
    self.paraDic[kVideoProfile] = @(videoProfile);
    self.paraDic[kMaxBandWidth] = @(maxCodeRate);
    self.paraDic[@"MinBandWidth"] = @(minCodeRate);
    self.paraDic[kUserType] = @(LarkMeetingManager.observerIndex);
    self.paraDic[@"SessionType"] = @(sessionType);
    self.paraDic[@"VideoCodecType"] = @(codeType);
    self.paraDic[kCloseCamera] = @(LarkMeetingManager.closeCameraIndex);
    self.paraDic[kGPUFilter] = @(isGPUFilter);
    self.paraDic[@"SRTPEncrypt"] = @(isSRTPEncrypt);
}

- (void)joinChannel
{
    [self initUserDefaultsData];
    [self configParameter];
    [self.rongRTCEngine setVideoParameters:self.paraDic];
    self.userID = [CommonUtility hardwareUUID];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    self.userName = [userDefaults valueForKey:@"UserInputName"];
    
    DLog(@"LLH..... UUID: %@  userName: %@", self.userID, self.userName);
    [self.rongRTCEngine joinChannel:self.channelID withKeyToken:[LogonViewController getKeyToken] withUserID:self.userID withUserName:self.userName];
    [self stopCallingBreath];
    
    if (LarkMeetingManager.observerIndex == RongRTC_User_Observer)
        [self.leftMVControlCollectionViewDelegateSource turnCollectionViewItemToObserver];
    
    [self.rongRTCEngine setVideoSizeForTinyStream:176 height:144];
}

- (void)loadLocalVideoView
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (LarkMeetingManager.observerIndex == RongRTC_User_Normal || LarkMeetingManager.observerIndex == RongRTC_User_Host)
        {
            self.meetingViewBuilder.localVideoView = [self.rongRTCEngine createLocalVideoViewFrame:CGRectMake(0, 0, kVideoWidth, kVideoHeight) withDisplayType:RongRTC_VideoViewDisplay_CompleteView];
            AppDelegate *appDelegate = (AppDelegate *)[NSApplication sharedApplication].delegate;
            [appDelegate.childWindow.contentView addSubview:self.meetingViewBuilder.localVideoView];
            //            [self.rongRTCEngine closeLocalVideo:!self.closeCameraIndex];
            
            self.localVideoViewModel = nil;
            self.localVideoViewModel = [[MeetingVideoViewModel alloc] initWithView:self.meetingViewBuilder.localVideoView];
            self.localVideoViewModel.userID = self.userID;
            self.localVideoViewModel.userName = self.userName;
            self.localVideoViewModel.userType = RongRTC_User_Normal;
            self.localVideoViewModel.avType = LarkMeetingManager.closeCameraIndex;
            self.localVideoViewModel.originalSize = CGSizeMake(localVideoWidth, localVideoHeight);
            
            NSColor *headColor = [NSColor randomColorForAvatarRBG];
            self.localVideoViewModel.headIconView = [[HeadIconView alloc] initWithFrame:RightTableHeaderFrame withUserName:self.localVideoViewModel.userName withColor:headColor];
            self.localVideoViewModel.switchHeadIconView = [[HeadIconView alloc] initWithFrame:SwitchPageHeaderFrame withUserName:self.localVideoViewModel.userName withColor:headColor];
            self.localVideoViewModel.micImageView = self.localVideoViewModel.switchHeadIconView;
        }
    });
}

- (void)modifyAudioVideoType
{
    LarkMeetingManager.isCloseCamera = !LarkMeetingManager.isCloseCamera;
    [self.rongRTCEngine closeLocalVideo:LarkMeetingManager.isCloseCamera];
    RongRTCAudioVideoType avType = LarkMeetingManager.isCloseCamera ? RongRTC_User_Only_Audio : RongRTC_User_Audio_Video;
    [self.rongRTCEngine modifyAudioVideoType:avType];
//    self.localView.hidden = self.isCloseCamera;
//    [self switchButtonBackgroundColor:self.isCloseCamera button:btn];
    
    if (LarkMeetingManager.isCloseCamera)
    {
        self.localVideoViewModel.micImageView.frame = CGRectMake((kVideoWidth-kCellSize)/2, (kVideoHeight-kCellSize)/2, self.localVideoViewModel.micImageView.frame.size.width, self.localVideoViewModel.micImageView.frame.size.height);
        [self.mainView addSubview:self.localVideoViewModel.micImageView];
    }
    else
    {
        [self.localVideoViewModel.micImageView removeFromSuperview];
    }
    
    if (LarkMeetingManager.isCloseCamera)
        [self switchLeftMVCollectionViewItem:6 withLabelColor:kThemeColor withImageName:@"MeetingMenu6CameraBlue"];
    else
        [self switchLeftMVCollectionViewItem:6 withLabelColor:[NSColor blackColor] withImageName:@"MeetingMenu6CameraGray"];
}

- (void)updateAudioVideoType:(RongRTCAudioVideoType)type
{
    switch (type)
    {
        case RongRTC_User_Only_Audio:
            LarkMeetingManager.isCloseCamera = YES;
            LarkMeetingManager.is7Mute = NO;
            break;
        case RongRTC_User_Audio_Video_None:
            LarkMeetingManager.isCloseCamera = YES;
            LarkMeetingManager.is7Mute = YES;
            break;
        case RongRTC_User_Audio_Video:
            LarkMeetingManager.isCloseCamera = NO;
            LarkMeetingManager.is7Mute = NO;
            break;
        case RongRTC_User_Only_Video:
            LarkMeetingManager.isCloseCamera = NO;
            LarkMeetingManager.is7Mute = YES;
            break;
        default:
            break;
    }
    
    if (LarkMeetingManager.isCloseCamera)
        [self switchLeftMVCollectionViewItem:6 withLabelColor:kThemeColor withImageName:@"MeetingMenu6CameraBlue"];
    else
        [self switchLeftMVCollectionViewItem:6 withLabelColor:[NSColor blackColor] withImageName:@"MeetingMenu6CameraGray"];
    
    if (LarkMeetingManager.is7Mute)
        [self switchLeftMVCollectionViewItem:7 withLabelColor:kThemeColor withImageName:@"MeetingMenu7MuteBlue"];
    else
        [self switchLeftMVCollectionViewItem:7 withLabelColor:[NSColor blackColor] withImageName:@"MeetingMenu7MuteGray"];
    
    [self.rongRTCEngine closeLocalVideo:LarkMeetingManager.isCloseCamera];
    [self.rongRTCEngine muteMicrophone:LarkMeetingManager.is7Mute];
    
    if (LarkMeetingManager.isCloseCamera)
    {
        if (LarkMeetingManager.isSwitchVideoView)
        {
            self.localVideoViewModel.micImageView.frame = CGRectMake(0, 0, self.localVideoViewModel.micImageView.frame.size.width, self.localVideoViewModel.micImageView.frame.size.height);
        }
        else
        {
            CGSize size = self.localVideoViewModel.micImageView.frame.size;
            if (LarkMeetingManager.isFullScreen)
                self.localVideoViewModel.micImageView.frame = CGRectMake((kScreenWidth - size.width)/2, (kScreenHeight - size.height)/2, size.width, size.height);
            else
                self.localVideoViewModel.micImageView.frame = CGRectMake((kVideoWidth - size.width)/2, (kVideoHeight - size.height)/2, size.width, size.height);
        }
        
        [self.localVideoViewModel.cellVideoView addSubview:self.localVideoViewModel.micImageView];
    }
    else
        [self.localVideoViewModel.micImageView removeFromSuperview];
    
    if (LarkMeetingManager.is4ShareScreen)
    {
        [self.rongRTCEngine stopScreenShare];
        [self switchLeftMVCollectionViewItem:4 withLabelColor:[NSColor blackColor] withImageName:@"MeetingMenu4ShareGray"];
        [self.meetingViewBuilder.screenShareMessageTextField removeFromSuperview];
        LarkMeetingManager.is4ShareScreen = !LarkMeetingManager.is4ShareScreen;
    }
}

- (void)setRepresentedObject:(id)representedObject
{
    [super setRepresentedObject:representedObject];
}

#pragma mark - 修改信号强度级别
- (void)modifySignalLevel:(NSInteger)level
{
//    DLog(@"LLH...... modifySignalLevel: %zd", level);
    switch (level)
    {
        case -1:
            self.meetingViewBuilder.signalImageView.image = signalImageDis;
            break;
        case 0:
            self.meetingViewBuilder.signalImageView.image = signalImage0;
            break;
        case 1:
            self.meetingViewBuilder.signalImageView.image = signalImage1;
            break;
        case 2:
            self.meetingViewBuilder.signalImageView.image = signalImage2;
            break;
        case 3:
            self.meetingViewBuilder.signalImageView.image = signalImage3;
            break;
        case 4:
            self.meetingViewBuilder.signalImageView.image = signalImage4;
            break;
        case 5:
            self.meetingViewBuilder.signalImageView.image = signalImage5;
            break;
        default:
            break;
    }
}

#pragma mark - 开始呼叫呼吸
- (void)startCallingBreath:(NSString *)userID block:(ApplyRequestBlock)block
{
    if (LarkMeetingManager.isCallingBreath)
        return;
    
    LarkMeetingManager.isCallingBreath = YES;
    applyRequestBlock = block;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.mainView addSubview:self.meetingViewBuilder.callingBreathImageView];
        [self.mainView addSubview:self.meetingViewBuilder.callingHungUpButton];
        [self.mainView addSubview:self.meetingViewBuilder.callingAcceptButton];
        
        MeetingVideoViewModel *model = [LarkMeetingManager getRemoteAllMemberArrayObject:userID];
        if (model)
        {
            HeadIconView *callingHeadIconView = model.switchHeadIconView;
            callingHeadIconView.frame = CGRectMake((self.meetingViewBuilder.callingBreathImageView.frame.size.width - callingHeadIconView.frame.size.width)/2, (self.meetingViewBuilder.callingBreathImageView.frame.size.height - callingHeadIconView.frame.size.height)/2, callingHeadIconView.frame.size.width, callingHeadIconView.frame.size.height);
            callingHeadIconView.wantsLayer = YES;
            callingHeadIconView.layer.cornerRadius = callingHeadIconView.frame.size.width / 2;
            [self.meetingViewBuilder.callingBreathImageView addSubview:callingHeadIconView];
        }
        
        breathTimer = [NSTimer scheduledTimerWithTimeInterval:0.3f target:self selector:@selector(setBreathImage) userInfo:nil repeats:YES];
        endBreathTimer = [NSTimer scheduledTimerWithTimeInterval:30.0f target:self selector:@selector(endBreathTimerAction) userInfo:nil repeats:NO];
    });
}

#pragma mark - 停止呼叫呼吸
- (void)stopCallingBreath
{
    DLog(@"LLH...... stopCallingBreath");
    LarkMeetingManager.isCallingBreath = NO;
    applyRequestBlock = nil;
    [breathTimer invalidate];
    breathTimer = nil;
    [endBreathTimer invalidate];
    endBreathTimer = nil;
    [self.meetingViewBuilder.callingBreathImageView removeFromSuperview];
    [self.meetingViewBuilder.callingHungUpButton removeFromSuperview];
    [self.meetingViewBuilder.callingAcceptButton removeFromSuperview];
}

#pragma mark - 设置呼叫呼吸闪烁
- (void)setBreathImage
{
    if (callingBreathLevel <= 5)
        callingBreathLevel++;
    else
        callingBreathLevel = 1;
    
    switch (callingBreathLevel)
    {
        case 1:
            self.meetingViewBuilder.callingBreathImageView.image = [NSImage imageNamed:@"MeetingCalling1"];
            break;
        case 2:
            self.meetingViewBuilder.callingBreathImageView.image = [NSImage imageNamed:@"MeetingCalling2"];
            break;
        case 3:
            self.meetingViewBuilder.callingBreathImageView.image = [NSImage imageNamed:@"MeetingCalling3"];
            break;
        case 4:
            self.meetingViewBuilder.callingBreathImageView.image = [NSImage imageNamed:@"MeetingCalling4"];
            break;
        case 5:
            self.meetingViewBuilder.callingBreathImageView.image = [NSImage imageNamed:@"MeetingCalling3"];
            break;
        case 6:
            self.meetingViewBuilder.callingBreathImageView.image = [NSImage imageNamed:@"MeetingCalling2"];
            break;
        default:
            break;
    }
}

#pragma mark - 呼叫等待超时 主动停止呼吸事件(主持人)
- (void)endBreathTimerAction
{
    if (applyRequestBlock)
        applyRequestBlock(NO);
    
    [self stopCallingBreath];
    
    if ([LarkMeetingManager isHandupRequestArrayContainObject:self.requestUpgradeUserID])
        [LarkMeetingManager removeHandupRequestArrayObject:self.requestUpgradeUserID];
    
    dispatch_semaphore_signal(self.semaphore);
}

#pragma mark - 主持人打开/关闭正常用户麦克风
- (void)controlMemberMicphone:(NSString *)userID status:(BOOL)isOpen
{
    [self.rongRTCEngine hostControlUserDevice:userID withDeviceType:RongRTC_Device_Micphone open:isOpen];
}

#pragma mark - 主持人打开/关闭正常用户摄像头
- (void)controlMemberCamera:(NSString *)userID status:(BOOL)isOpen
{
    [self.rongRTCEngine hostControlUserDevice:userID withDeviceType:RongRTC_Device_Camera open:isOpen];
}

#pragma mark - 主持人将正常用户降级为观察者
- (void)degradeMemberToObserver:(NSString *)userID
{
    [self.rongRTCEngine degradeNormalUserToObserver:userID];
}

#pragma mark - 主持人将观察者升级为正常用户
- (void)upgradeMemberToNormal:(NSString *)userID
{
    [self.rongRTCEngine upgradeObserverToNormalUser:userID];
//    for (MeetingVideoViewModel *model in self.remoteAllMemberArray)
//    {
//        if ([userID isEqualToString:model.userID])
//        {
//            model.userType = RongRTC_User_Normal;
//            model.headerImage = [NSImage imageNamed:@"MeetingMemberNormal"];
//        }
//    }
//    [self.meetingViewBuilder.rightTableView reloadData];
}

#pragma mark - 主持人将用户踢出房间
- (void)removeAttendedMember:(NSString *)userID
{
    [self.rongRTCEngine removeUser:userID];
}

#pragma mark - 呼叫挂断点击事件
- (void)callingHungUpButtonPressed
{
    DLog(@"LLH...... callingHungUpButtonPressed");
    if (applyRequestBlock)
    {
        applyRequestBlock(NO);
        applyRequestBlock = nil;
    }
    
    [self stopCallingBreath];
}

#pragma mark - 呼叫接听点击事件
- (void)callingAcceptButtonPressed
{
    DLog(@"LLH...... callingAcceptButtonPressed");
    if (applyRequestBlock)
    {
        applyRequestBlock(YES);
        applyRequestBlock = nil;
    }
    
    [self stopCallingBreath];
}

#pragma mark - 弹出提示窗
- (void)showMessageAlert:(NSString *)text title:(NSString *)title completedBlock:(MessageAlertBlock)block
{
    /*
    DLog(@"LLH...... showMessageAlert: %@", text);
    [self.meetingViewBuilder.confirmMessagePanel orderOut:nil];
    [self.meetingViewBuilder.alertMessagePanel orderOut:nil];
    [messageAlertTextField removeFromSuperview];
    messageAlertTextField = nil;
    self.meetingViewBuilder.confirmMessagePanel.title = title;
    messageAlertBlock = block;
    
    NSTextField *textField = [[NSTextField alloc] initWithFrame:CGRectMake(0, 60, self.meetingViewBuilder.confirmMessagePanel.frame.size.width, 60)];
    textField.stringValue = text;
    textField.bordered = NO;
    textField.editable = NO;
    textField.alignment = NSTextAlignmentCenter;
    textField.font = [NSFont systemFontOfSize:14.0];
    textField.backgroundColor = [NSColor clearColor];
    //    messageTextField.textColor = kLogonTextColor;
    messageAlertTextField = textField;
    [self.meetingViewBuilder.confirmMessagePanel.contentView addSubview:textField];
    
    //    messageTextField.wantsLayer = YES;
    //    messageTextField.layer.backgroundColor = [NSColor greenColor].CGColor;
    [self.meetingViewBuilder.confirmMessagePanel makeKeyAndOrderFront:nil];
    */
    
    DLog(@"LLH...... showMessageAlert: %@", text);
    [self.meetingViewBuilder.confirmMessageWindow orderOut:nil];
    [self.meetingViewBuilder.alertMessageWindow orderOut:nil];
    [messageAlertTextField removeFromSuperview];
    messageAlertTextField = nil;
    self.meetingViewBuilder.confirmMessageWindow.title = title;
    messageAlertBlock = block;
    
    NSTextField *textField = [[NSTextField alloc] initWithFrame:CGRectMake(0, 60, self.meetingViewBuilder.confirmMessageWindow.frame.size.width, 60)];
    textField.stringValue = text;
    textField.bordered = NO;
    textField.editable = NO;
    textField.alignment = NSTextAlignmentCenter;
    textField.font = [NSFont systemFontOfSize:14.0];
    textField.backgroundColor = [NSColor clearColor];
    messageAlertTextField = textField;
    [self.meetingViewBuilder.confirmMessageWindow.contentView addSubview:textField];
    [self.meetingViewBuilder.confirmMessageWindow makeKeyAndOrderFront:self];
    [self.meetingViewBuilder.confirmMessageWindow center];
    
    [[NSApplication sharedApplication] runModalForWindow:self.meetingViewBuilder.confirmMessageWindow];
}

- (void)showMessageAlertSingle:(NSString *)text title:(NSString *)title
{
    /*
    DLog(@"LLH...... showMessageAlertSingle: %@", text);
    [self.meetingViewBuilder.confirmMessagePanel orderOut:nil];
    [self.meetingViewBuilder.alertMessagePanel orderOut:nil];
    [messageAlertTextField removeFromSuperview];
    messageAlertTextField = nil;
    self.meetingViewBuilder.alertMessagePanel.title = title;
    
    NSTextField *textField = [[NSTextField alloc] initWithFrame:CGRectMake(0, 60, self.meetingViewBuilder.confirmMessagePanel.frame.size.width, 60)];
    textField.stringValue = text;
    textField.bordered = NO;
    textField.editable = NO;
    textField.alignment = NSTextAlignmentCenter;
    textField.font = [NSFont systemFontOfSize:14.0];
    //    messageTextField.textColor = kLogonTextColor;
    messageAlertTextField = textField;
    [self.meetingViewBuilder.alertMessagePanel.contentView addSubview:textField];
    
    //    messageTextField.wantsLayer = YES;
    //    messageTextField.layer.backgroundColor = [NSColor greenColor].CGColor;
    [self.meetingViewBuilder.alertMessagePanel makeKeyAndOrderFront:nil];
     */
    
    DLog(@"LLH...... showMessageAlertSingle: %@", text);
    [self.meetingViewBuilder.confirmMessageWindow orderOut:nil];
    [self.meetingViewBuilder.alertMessageWindow orderOut:nil];
    [messageAlertTextField removeFromSuperview];
    messageAlertTextField = nil;
    self.meetingViewBuilder.alertMessageWindow.title = title;
    
    NSTextField *textField = [[NSTextField alloc] initWithFrame:CGRectMake(0, 60, self.meetingViewBuilder.confirmMessageWindow.frame.size.width, 60)];
    textField.stringValue = text;
    textField.bordered = NO;
    textField.editable = NO;
    textField.alignment = NSTextAlignmentCenter;
    textField.font = [NSFont systemFontOfSize:14.0];
    textField.backgroundColor = [NSColor clearColor];
    messageAlertTextField = textField;
    [self.meetingViewBuilder.alertMessageWindow.contentView addSubview:textField];
    [self.meetingViewBuilder.alertMessageWindow makeKeyAndOrderFront:self];
    [self.meetingViewBuilder.alertMessageWindow center];
    
    [[NSApplication sharedApplication] runModalForWindow:self.meetingViewBuilder.alertMessageWindow];
}

#pragma mark - 提示窗选择是
- (void)messageAlertYes
{
    DLog(@"LLH...... messageAlertYes");
    [messageAlertTextField removeFromSuperview];
    messageAlertTextField = nil;
    [self.meetingViewBuilder.confirmMessageWindow orderOut:nil];
    [[NSApplication sharedApplication] stopModal];
    messageAlertBlock(YES);
//    [self.view.window orderFront:nil];
}

#pragma mark - 提示窗选择否
- (void)messageAlertNo
{
    DLog(@"LLH...... messageAlertNo");
    [messageAlertTextField removeFromSuperview];
    messageAlertTextField = nil;
    [self.meetingViewBuilder.confirmMessageWindow orderOut:nil];
    [[NSApplication sharedApplication] stopModal];
    if (messageAlertBlock) {
        messageAlertBlock(NO);
    }
//    [self.view.window orderFront:nil];
}

#pragma mark - 单按钮提示窗选择是
- (void)messageAlertSingleYes
{
    DLog(@"LLH...... messageAlertNo");
    [messageAlertTextField removeFromSuperview];
    messageAlertTextField = nil;
    [self.meetingViewBuilder.alertMessageWindow orderOut:nil];
    [[NSApplication sharedApplication] stopModal];
//    [self.view.window orderFront:nil];
}

#pragma mark - 添加会议室消息
- (void)addTipMsg:(NSString *)userName withMessageType:(RongRTCMessageType)type
{
    NSString *time = [CommonUtility formatTimeFromDate:[NSDate date] withFormat:@"HH:mm:ss"];
    NSString *msg = @"";
    switch (type)
    {
        case RongRTC_Message_Join:
            msg = [NSString stringWithFormat:@"%@\n%@%@\n\n", time, userName, NSLocalizedString(@"meeting_msg_1", nil)];
            break;
        case RongRTC_Message_Leave:
            msg = [NSString stringWithFormat:@"%@\n%@%@\n\n", time, userName, NSLocalizedString(@"meeting_msg_2", nil)];
            break;
//        case RongRTC_Message_Upgrade:
//            msg = [NSString stringWithFormat:@"%@\n%@升级为正常用户\n\n", time, userName];
//            break;
//        case RongRTC_Message_Degrade:
//            msg = [NSString stringWithFormat:@"%@\n%@降级为观察者\n\n", time, userName];
//            break;
        case RongRTC_Message_WhiteBoard:
            msg = [NSString stringWithFormat:@"%@\n%@%@\n\n", time, userName, NSLocalizedString(@"meeting_msg_3", nil)];
            break;
        case RongRTC_Message_StartScreenShare:
            msg = [NSString stringWithFormat:@"%@\n%@%@\n\n", time, userName, NSLocalizedString(@"meeting_msg_4", nil)];
            break;
        case RongRTC_Message_StopScreenShare:
            msg = [NSString stringWithFormat:@"%@\n%@%@\n\n", time, userName, NSLocalizedString(@"meeting_msg_5", nil)];
            break;
        case RongRTC_Message_Host:
            msg = [NSString stringWithFormat:@"%@\n%@%@\n\n", time, userName, NSLocalizedString(@"meeting_msg_6", nil)];
            break;
        case RongRTC_Message_Alone:
            msg = [NSString stringWithFormat:@"%@\n%@\n\n", time, NSLocalizedString(@"meeting_msg_7", nil)];
            break;
        default:
            return;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.meetingViewBuilder.tipMsgTextView setEditable:YES];
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:msg];
        [self.meetingViewBuilder.tipMsgTextView insertText:attributedString];
        [self.meetingViewBuilder.tipMsgTextView setEditable:NO];
        [self.meetingViewBuilder.tipMsgTextView setSelectable:NO];
    });
}

#pragma mark - 视频向左移动点击事件
- (void)leftScrollButtonPressed
{
    DLog(@"LLH...... 左左左......");
    [self.meetingViewBuilder.switchPageViewControl moveLeftSwitchPage];
}

#pragma mark - 视频向右移动点击事件
- (void)rightScrollButtonPressed
{
    DLog(@"LLH...... 右右右......");
    [self.meetingViewBuilder.switchPageViewControl moveRightSwitchPage];
}

#pragma mark - 向下隐藏/向上显示视频View点击事件
- (void)downVideosBottomButtonPressed
{
    CGRect orignalFreme = self.meetingViewBuilder.videosBottomView.frame;
    if (orignalFreme.origin.y == 0-kCellSize)
    {
        DLog(@"LLH...... 上上上......");
        [self.meetingViewBuilder.downVideosBottomButton setImage:[NSImage imageNamed:@"MeetingDownVideoBottomButton"]];
        self.meetingViewBuilder.videosBottomView.frame = CGRectMake(orignalFreme.origin.x, 0, orignalFreme.size.width, orignalFreme.size.height);
//        self.meetingViewBuilder.videosBottomView.backgroundColor = kVideoViewColor;
    }
    else
    {
        DLog(@"LLH...... 下下下......");
        [self.meetingViewBuilder.downVideosBottomButton setImage:[NSImage imageNamed:@"MeetingUpVideoBottomButton"]];
        self.meetingViewBuilder.videosBottomView.frame = CGRectMake(orignalFreme.origin.x, 0-kCellSize, orignalFreme.size.width, orignalFreme.size.height);
//        self.meetingViewBuilder.videosBottomView.backgroundColor = [NSColor clearColor];
    }
}

#pragma mark - 隐藏/显示右侧控制面板点击事件
- (void)hideControlViewButtonPressed
{
    CGFloat rightOperationViewWidth = 840 - kVideoWidth;
    DLog(@"LLH...... hideControlViewButtonPressed: %zd", LarkMeetingManager.isHideControlView);
    LarkMeetingManager.isHideControlView = !LarkMeetingManager.isHideControlView;
    
    NSViewAnimation *theAnim;
    NSRect firstViewFrame;
    NSRect newViewFrame;
    NSMutableDictionary *firstViewDict;
    {
        firstViewDict = [NSMutableDictionary dictionaryWithCapacity:3];
        firstViewFrame = [self.meetingViewBuilder.rightContentView frame];
        [firstViewDict setObject:self.meetingViewBuilder.rightContentView forKey:NSViewAnimationTargetKey];
        
        //设置视图的起始位置
        [firstViewDict setObject:[NSValue valueWithRect:firstViewFrame] forKey:NSViewAnimationStartFrameKey];
        
        // 改变视图1的位置，并把改变之后的位置变为视图结束位置
        newViewFrame = firstViewFrame;
        if (LarkMeetingManager.isHideControlView)
        {
            DLog(@"LLH...... hideControlViewButtonPressed: 关闭控制面板");
            //隐藏右侧面板动画
            newViewFrame.origin.x += rightOperationViewWidth;
            
            [self.meetingViewBuilder.hideControlViewButton setImage:[NSImage imageNamed:@"MeetingHideControlViewLeft"]];
            
            self.meetingViewBuilder.whiteBoardWebView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
            [[self.meetingViewBuilder.whiteBoardWebView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.meetingViewBuilder.whiteBoardWebView.mainFrameURL]]];
        }
        else
        {
            DLog(@"LLH...... hideControlViewButtonPressed: 打开控制面板");
            //显示右侧面板动画
            newViewFrame.origin.x -= rightOperationViewWidth;
            [self.meetingViewBuilder.hideControlViewButton setImage:[NSImage imageNamed:@"MeetingHideControlViewRight"]];
            
            self.meetingViewBuilder.whiteBoardWebView.frame = CGRectMake(0, 0, kScreenWidth-200, kScreenHeight);
            [[self.meetingViewBuilder.whiteBoardWebView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.meetingViewBuilder.whiteBoardWebView.mainFrameURL]]];
        }
        
//        newViewFrame.origin.y += 0;
        [firstViewDict setObject:[NSValue valueWithRect:newViewFrame] forKey:NSViewAnimationEndFrameKey];
        
        theAnim = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObjects:firstViewDict, nil]];
        
        // 设置动画的一些属性.比如持续时间0.5秒
        [theAnim setDuration:0.5];
        [theAnim setAnimationCurve:NSAnimationEaseIn];
        
        // 启动动画
        [theAnim startAnimation];
    }
}

#pragma mark - 左侧会场消息点击事件
- (void)leftMessageButtonPressed
{
    self.meetingViewBuilder.leftMessageButton.wantsLayer = YES;
    self.meetingViewBuilder.leftMessageButton.layer.backgroundColor = kThemeColor.CGColor;
    self.meetingViewBuilder.rightMemberButton.wantsLayer = YES;
    self.meetingViewBuilder.rightMemberButton.layer.backgroundColor = [NSColor lightGrayColor].CGColor;
    [self.meetingViewBuilder.leftMessageView removeFromSuperview];
    [self.meetingViewBuilder.rightContentView addSubview:self.meetingViewBuilder.leftMessageView];
}

#pragma mark - 右侧与会成员点击事件
- (void)rightMemberButtonPressed
{
    self.meetingViewBuilder.leftMessageButton.wantsLayer = YES;
    self.meetingViewBuilder.leftMessageButton.layer.backgroundColor = [NSColor lightGrayColor].CGColor;
    self.meetingViewBuilder.rightMemberButton.wantsLayer = YES;
    self.meetingViewBuilder.rightMemberButton.layer.backgroundColor = kThemeColor.CGColor;
    [self.meetingViewBuilder.rightMemberView removeFromSuperview];
    [self.meetingViewBuilder.rightContentView addSubview:self.meetingViewBuilder.rightMemberView];
}

#pragma mark - 声音消息按钮点击事件
- (void)leftMVVoiceButtonPressed
{
    DLog(@"LLH...... leftMVVoiceButtonPressed");
}

#pragma mark - 消息发送按钮点击事件
- (void)leftMVSendButtonPressed
{
    DLog(@"LLH...... leftMVSendButtonPressed");
}

#pragma mark - 0请求发言
- (void)requestSpeakButtonPressed
{
    DLog(@"LLH...... requestSpeakButtonPressed");
//    self.is0RequestSpeak = !self.is0RequestSpeak;
//    if (self.is0RequestSpeak)
//        [self switchLeftMVCollectionViewItem:0 withLabelColor:kThemeColor withImageName:@"MeetingMenu0HandsUpBlue"];
//    else
//        [self switchLeftMVCollectionViewItem:0 withLabelColor:[NSColor blackColor] withImageName:@"MeetingMenu0HandsUpGray"];
    
    if (LarkMeetingManager.observerIndex != RongRTC_User_Observer)
    {
        DLog(@"LLH...... requestSpeakButtonPressed RongRTC_User_Observer return");
//        [self showMessageAlertSingle:[NSTextField labelWithString:@"正常用户不用请求,可直接发言!"] title:NSLocalizedString(@"meeting_speach_request", nil)];
        return;
    }

//    [self showMessageAlert:[NSTextField labelWithString:@"是否向主持人请求发言?"] title:NSLocalizedString(@"meeting_speach_request", nil) completedBlock:^(BOOL selected) {
//        if (selected)
            [self.rongRTCEngine observerRequestBecomeNormalUser];
//    }];
}

#pragma mark - 1邀请
- (void)inviteButtonPressed
{
    DLog(@"LLH...... inviteButtonPressed");
//    self.is1Invite = !self.is1Invite;
//    if (self.is1Invite)
//        [self switchLeftMVCollectionViewItem:1 withLabelColor:kThemeColor withImageName:@"MeetingMenu1InviteBlue"];
//    else
//        [self switchLeftMVCollectionViewItem:1 withLabelColor:[NSColor blackColor] withImageName:@"MeetingMenu1InviteGray"];
    
    [self.rongRTCEngine getInviteURL];
}

#pragma mark - 2主持会议
- (void)manageMeetingButtonPressed
{
    DLog(@"LLH...... manageMeetingButtonPressed");
//    self.is2ManageMeeting = !self.is2ManageMeeting;
//    if (self.is2ManageMeeting)
//        [self switchLeftMVCollectionViewItem:5 withLabelColor:kThemeColor withImageName:@"MeetingMenu5UploadBlue"];
//    else
//        [self switchLeftMVCollectionViewItem:5 withLabelColor:[NSColor blackColor] withImageName:@"MeetingMenu5UploadGray"];
    
    if (LarkMeetingManager.observerIndex == RongRTC_User_Observer)
    {
        DLog(@"LLH...... manageMeetingButtonPressed RongRTC_User_Observer return");
//        [self showMessageAlertSingle:[NSTextField labelWithString:@"观察者无法主持会议!"] title:NSLocalizedString(@"meeting_host_meeting", nil)];
        return;
    }
    if (LarkMeetingManager.observerIndex == RongRTC_User_Host)
    {
        DLog(@"LLH...... manageMeetingButtonPressed RongRTC_User_Host return");
//        [self showMessageAlertSingle:[NSTextField labelWithString:@"你已经是主持人!"] title:NSLocalizedString(@"meeting_host_meeting", nil)];
        return;
    }
    
    [self showMessageAlert:NSLocalizedString(@"meeting_msg_8", nil) title:NSLocalizedString(@"meeting_host_meeting", nil) completedBlock:^(BOOL selected) {
        if (selected)
            [self.rongRTCEngine normalUserRequestHostAuthority];
    }];
}

#pragma mark - 3使用白板
- (void)useWhiteBoardButtonPressed
{
    if (LarkMeetingManager.observerIndex == RongRTC_User_Observer && !LarkMeetingManager.isWhiteBoardExist)
    {
        [self showMessageAlertSingle:NSLocalizedString(@"meeting_msg_9", nil) title:NSLocalizedString(@"meeting_white_board", nil)];
        return;
    }
    
    DLog(@"LLH...... useWhiteBoardButtonPressed");
    LarkMeetingManager.isWhiteBoardExist = YES;
    LarkMeetingManager.is3UseWhiteBoard = !LarkMeetingManager.is3UseWhiteBoard;
    CGRect orignalFreme = self.meetingViewBuilder.videosBottomView.frame;
    
    if (LarkMeetingManager.is3UseWhiteBoard)
    {
        if (orignalFreme.origin.y != 0-kCellSize)
            [self downVideosBottomButtonPressed];
        
        [self.rongRTCEngine requestWhiteBoardURL];
        self.meetingViewBuilder.whiteBoardWebView = [[WebView alloc] initWithFrame:CGRectMake(0, 0, kVideoWidth, kVideoHeight)];
        
        if (LarkMeetingManager.isFullScreen)
            self.meetingViewBuilder.whiteBoardWebView = [[WebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth-200, kScreenHeight)];
        else
            self.meetingViewBuilder.whiteBoardWebView = [[WebView alloc] initWithFrame:CGRectMake(0, 0, kVideoWidth, kVideoHeight)];
        
        self.meetingViewBuilder.whiteBoardWebView.UIDelegate = self.whiteBoardWebUIDelegateImpl;
//        self.meetingViewBuilder.whiteBoardWebView.resourceLoadDelegate = self.whiteBoardWebUIDelegateImpl;
        [self switchLeftMVCollectionViewItem:3 withLabelColor:kThemeColor withImageName:@"MeetingMenu3WhiteBoardBlue"];
    }
    else
    {
        [self.meetingViewBuilder.whiteBoardWebView removeFromSuperview];
        [self downVideosBottomButtonPressed];
        [self switchLeftMVCollectionViewItem:3 withLabelColor:[NSColor blackColor] withImageName:@"MeetingMenu3WhiteBoardGray"];
    }
}

#pragma mark - 4共享屏幕
- (void)shareScreenButtonPressed
{
    DLog(@"LLH...... shareScreenButtonPressed");
    
    if (LarkMeetingManager.isCloseCamera)
    {
        [self showMessageAlertSingle:NSLocalizedString(@"meeting_msg_10", nil) title:NSLocalizedString(@"meeting_share_screen", nil)];
        return;
    }
    
    LarkMeetingManager.is4ShareScreen = !LarkMeetingManager.is4ShareScreen;
    
    if (LarkMeetingManager.is4ShareScreen)
    {
        [self.rongRTCEngine startScreenShare];
        [self switchLeftMVCollectionViewItem:4 withLabelColor:kThemeColor withImageName:@"MeetingMenu4ShareBlue"];
        self.meetingViewBuilder.screenShareMessageTextField.frame = CGRectMake(0, (self.localVideoViewModel.cellVideoView.frame.size.height - 20)/2, self.localVideoViewModel.cellVideoView.frame.size.width, 20);
        [self.localVideoViewModel.cellVideoView addSubview:self.meetingViewBuilder.screenShareMessageTextField];
        
        if (LarkMeetingManager.isSwitchVideoView)
            self.meetingViewBuilder.screenShareMessageTextField.font = [NSFont systemFontOfSize:16.0];
        else
            self.meetingViewBuilder.screenShareMessageTextField.font = [NSFont systemFontOfSize:18.0];
    }
    else
    {
        [self.rongRTCEngine stopScreenShare];
        [self switchLeftMVCollectionViewItem:4 withLabelColor:[NSColor blackColor] withImageName:@"MeetingMenu4ShareGray"];
        [self.meetingViewBuilder.screenShareMessageTextField removeFromSuperview];
    }
}

#pragma mark - 5扬声器
- (void)videoRecordButtonPressed
{
    DLog(@"LLH...... videoRecordButtonPressed");
    [self.rongRTCEngine switchSpeaker:LarkMeetingManager.is5Speaker];
    LarkMeetingManager.is5Speaker = !LarkMeetingManager.is5Speaker;
    
    if (LarkMeetingManager.is5Speaker)
        [self switchLeftMVCollectionViewItem:5 withLabelColor:kThemeColor withImageName:@"MeetingMenu2VideoRecordBlue"];
    else
        [self switchLeftMVCollectionViewItem:5 withLabelColor:[NSColor blackColor] withImageName:@"MeetingMenu2VideoRecordGray"];
}

#pragma mark - 6摄像头
- (void)closeCameraButtonPressed
{
    DLog(@"LLH...... switchCameraButtonPressed");
    
    if (LarkMeetingManager.is4ShareScreen)
    {
        [self showMessageAlertSingle:NSLocalizedString(@"meeting_msg_11", nil) title:NSLocalizedString(@"meeting_share_screen", nil)];
        return;
    }
    
    LarkMeetingManager.isCloseCamera = !LarkMeetingManager.isCloseCamera;
    [self.rongRTCEngine closeLocalVideo:LarkMeetingManager.isCloseCamera];
//    RongRTCAudioVideoType avType = self.isCloseCamera ? RongRTC_User_Only_Audio : RongRTC_User_Audio_Video;
//    [self.rongRTCEngine modifyAudioVideoType:avType];
    [self.rongRTCEngine controlAudioVideoDevice:RongRTC_Device_Camera open:!LarkMeetingManager.isCloseCamera];
    
    if (LarkMeetingManager.isCloseCamera)
    {
        //[self.rongRTCEngine modifyAudioVideoType:RongRTC_User_Only_Audio];
        //[CommonUtility setButtonImage:btn imageName:@"chat_close_camera"];
        [self switchLeftMVCollectionViewItem:6 withLabelColor:kThemeColor withImageName:@"MeetingMenu6CameraBlue"];
        self.localVideoViewModel.avType = RongRTC_User_Only_Audio;
        
        if (LarkMeetingManager.isSwitchVideoView)
        {
            self.localVideoViewModel.micImageView.frame = CGRectMake(0, 0, self.localVideoViewModel.micImageView.frame.size.width, self.localVideoViewModel.micImageView.frame.size.height);
            [self.localVideoViewModel.cellVideoView addSubview:self.localVideoViewModel.micImageView];
        }
        else
        {
            self.localVideoViewModel.micImageView.frame = CGRectMake((kVideoWidth-kCellSize)/2, (kVideoHeight-kCellSize)/2, self.localVideoViewModel.micImageView.frame.size.width, self.localVideoViewModel.micImageView.frame.size.height);
            
            //if (whiteBoardWebView)
            //    [self.videoMainView bringSubviewToFront:whiteBoardWebView];
            AppDelegate *appDelegate = (AppDelegate *)[NSApplication sharedApplication].delegate;
            [appDelegate.childWindow.contentView addSubview:self.localVideoViewModel.micImageView];
        }
    }
    else
    {
        //[self.rongRTCEngine modifyAudioVideoType:RongRTC_User_Audio_Video];
        //[CommonUtility setButtonImage:btn imageName:@"chat_open_camera"];
        [self switchLeftMVCollectionViewItem:6 withLabelColor:[NSColor blackColor] withImageName:@"MeetingMenu6CameraGray"];
        self.localVideoViewModel.avType = RongRTC_User_Audio_Video;
        [self.localVideoViewModel.micImageView removeFromSuperview];
    }
}

#pragma mark - 7静音点击事件
- (void)muteButtonPressed
{
    DLog(@"LLH...... muteButtonPressed");
    LarkMeetingManager.is7Mute = !LarkMeetingManager.is7Mute;
    [self.rongRTCEngine muteMicrophone:LarkMeetingManager.is7Mute];
    [self.rongRTCEngine controlAudioVideoDevice:RongRTC_Device_Micphone open:!LarkMeetingManager.is7Mute];
    
    if (LarkMeetingManager.is7Mute)
        [self switchLeftMVCollectionViewItem:7 withLabelColor:kThemeColor withImageName:@"MeetingMenu7MuteBlue"];
    else
        [self switchLeftMVCollectionViewItem:7 withLabelColor:[NSColor blackColor] withImageName:@"MeetingMenu7MuteGray"];
}

#pragma mark - 8挂断点击事件
- (void)hungupButtonPressed
{
    DLog(@"LLH...... hungupButtonPressed: %zd", LarkMeetingManager.userIDArray.count);

    isJoinedChannel = NO;
    if (LarkMeetingManager.isWhiteBoardExist && LarkMeetingManager.userIDArray.count == 0 && LarkMeetingManager.observerIndex == RongRTC_User_Normal)
    {
        [self showMessageAlert:NSLocalizedString(@"meeting_msg_12", nil) title:NSLocalizedString(@"meeting_confirm_ok", nil) completedBlock:^(BOOL selected)
         {
             if (selected)
                 [self.rongRTCEngine leaveChannel];
         }];
    }
    else
        [self.rongRTCEngine leaveChannel];
}

- (void)leaveChannel
{
    if (LarkMeetingManager.isFullScreen)
    {
        LarkMeetingManager.isFullScreen = NO;
        [self transformToOriginalSize];
    }
    
    [LarkMeetingManager removeRemoteAllMemberArrayAllObject];
    [LarkMeetingManager removeUserIDArrayAllObject];
    [LarkMeetingManager removeUpgradeUserIDArrayAllObject];
    [LarkMeetingManager removeRemoteVideoViewArrayAllObject];
    
    if (self.localVideoViewModel.micImageView)
        [self.localVideoViewModel.micImageView removeFromSuperview];
    
    [self.meetingViewBuilder.localVideoView removeFromSuperview];

    if (LarkMeetingManager.is4ShareScreen)
    {
        [self.rongRTCEngine stopScreenShare];
        [self switchLeftMVCollectionViewItem:4 withLabelColor:[NSColor blackColor] withImageName:@"MeetingMenu4ShareGray"];
        [self.meetingViewBuilder.screenShareMessageTextField removeFromSuperview];
    }
    
    if (LarkMeetingManager.isDataInfoOpen)
    {
        [self.meetingViewBuilder.avInfoPanel orderOut:nil];
        [self.view.window orderFront:nil];
    }
    
    AppDelegate *appDelegate = (AppDelegate *)[NSApplication sharedApplication].delegate;
    [appDelegate.childWindow.contentView removeFromSuperview];
    [self.view.window removeChildWindow:appDelegate.childWindow];
    appDelegate.childWindow = nil;
    
    NSStoryboard *storyboard = [NSStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    LogonWindowController *logonWindowController = [storyboard instantiateControllerWithIdentifier:@"LogonWindowController"];
    //[logonWindowController.window setAnimationBehavior:NSWindowAnimationBehaviorDocumentWindow];
    
    appDelegate.mainWindowController = logonWindowController;
    [logonWindowController.window makeKeyAndOrderFront:nil];
    [self.view.window orderOut:nil];
    [self.view.window close];
}

#pragma mark - 9按钮点击切换图片
- (void)switchLeftMVCollectionViewItem:(NSInteger)index withLabelColor:(NSColor *)color withImageName:(NSString *)imageName
{
    LeftMVControlCollectionViewItem *collectionViewItem = (LeftMVControlCollectionViewItem *)self.leftMVControlCollectionViewDelegateSource.itemDic[@(index)];
    collectionViewItem.itemImageView.image = [NSImage imageNamed:imageName];
    collectionViewItem.itemLabel.textColor = color;
}

#pragma mark - 进入全屏
- (void)transformToFullScreen
{
    LarkMeetingManager.isFullScreen = YES;
    CGRect fullScreenRect = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    self.view.window.contentView.frame = fullScreenRect;
    [self.view.window setFrame:fullScreenRect display:YES animate:NO];
    self.mainView.frame = fullScreenRect;
    
    AppDelegate *appDelegate = (AppDelegate *)[NSApplication sharedApplication].delegate;
    appDelegate.childWindow.contentView.frame = fullScreenRect;
    [appDelegate.childWindow setFrame:fullScreenRect display:YES animate:NO];
    
    if (LarkMeetingManager.is4ShareScreen && !LarkMeetingManager.isSwitchVideoView)
    {
        self.meetingViewBuilder.screenShareMessageTextField.frame = CGRectMake(0, (kScreenHeight - 20)/2, kScreenWidth, 20);
        self.meetingViewBuilder.screenShareMessageTextField.font = [NSFont systemFontOfSize:18.0];
    }
    
    self.meetingViewBuilder.whiteBoardWebView.frame = CGRectMake(0, 0, kScreenWidth-200, kScreenHeight);
    [[self.meetingViewBuilder.whiteBoardWebView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.meetingViewBuilder.whiteBoardWebView.mainFrameURL]]];
    [self.meetingViewBuilder reloadMeetingViewToFullScreen];
    [self.meetingViewBuilder.switchPageViewControl reloadCellInPageView];
    
    if (LarkMeetingManager.isSwitchVideoView)
    {
        NSView *remoteVideoView = [self.rongRTCEngine changeRemoteVideoViewFrame:fullScreenRect withUserID:self.selectedViewModel.userID withDisplayType:RongRTC_VideoViewDisplay_CompleteView];
        [appDelegate.childWindow.contentView addSubview:remoteVideoView];
        
        if (self.selectedViewModel.avType == RongRTC_User_Only_Audio || self.selectedViewModel.avType == RongRTC_User_Audio_Video_None)
        {
            self.selectedViewModel.micImageView.frame = CGRectMake((kScreenWidth-kCellSize)/2, (kScreenHeight-kCellSize)/2, self.selectedViewModel.micImageView.frame.size.width, self.selectedViewModel.micImageView.frame.size.height);
            [remoteVideoView addSubview:self.selectedViewModel.micImageView];
        }
    }
    else
    {
        if (LarkMeetingManager.observerIndex == RongRTC_User_Observer)
        {
            self.localVideoViewModel.cellVideoView = [self.rongRTCEngine changeRemoteVideoViewFrame:fullScreenRect withUserID:self.localVideoViewModel.userID withDisplayType:RongRTC_VideoViewDisplay_CompleteView];
        }
        else
        {
            self.localVideoViewModel.cellVideoView = [self.rongRTCEngine changeLocalVideoViewFrame:fullScreenRect withDisplayType:RongRTC_VideoViewDisplay_CompleteView];
        }
        [appDelegate.childWindow.contentView addSubview:self.localVideoViewModel.cellVideoView];
        
        if (self.localVideoViewModel.avType == RongRTC_User_Only_Audio || self.localVideoViewModel.avType == RongRTC_User_Audio_Video_None)
        {
            self.localVideoViewModel.micImageView.frame = CGRectMake((kScreenWidth-kCellSize)/2, (kScreenHeight-kCellSize)/2, self.localVideoViewModel.micImageView.frame.size.width, self.localVideoViewModel.micImageView.frame.size.height);
            [self.localVideoViewModel.cellVideoView addSubview:self.localVideoViewModel.micImageView];
        }
    }
    
    /*
    //隐藏右侧面板动画
    NSViewAnimation *theAnim;
    NSRect firstViewFrame;
    NSRect newViewFrame;
    NSMutableDictionary *firstViewDict;
    {
        
        firstViewDict = [NSMutableDictionary dictionaryWithCapacity:3];
        firstViewFrame = [self.rightContentView frame];
        [firstViewDict setObject:self.rightContentView forKey:NSViewAnimationTargetKey];
        
        //设置视图的起始位置
        [firstViewDict setObject:[NSValue valueWithRect:firstViewFrame] forKey:NSViewAnimationStartFrameKey];
        
        // 改变视图1的位置，并把改变之后的位置变为视图结束位置
        newViewFrame = firstViewFrame;
        newViewFrame.origin.x += rightOperationViewWidth;
        newViewFrame.origin.y += 0;
        [firstViewDict setObject:[NSValue valueWithRect:newViewFrame] forKey:NSViewAnimationEndFrameKey];
    }
    
    theAnim = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObjects:firstViewDict, nil]];
    
    // 设置动画的一些属性.比如持续时间0.5秒
    [theAnim setDuration:1.5];
    [theAnim setAnimationCurve:NSAnimationEaseIn];
    
    // 启动动画
    [theAnim startAnimation];
    */
}

#pragma mark - 退出全屏
- (void)transformToOriginalSize
{
    LarkMeetingManager.isFullScreen = NO;
    CGRect originalSizeRect = CGRectMake(0, 0, 840, 480);
    [self.view.window setFrame:CGRectMake(0, 0, 840, 502) display:YES animate:NO];
    self.view.window.contentView.frame = originalSizeRect;
    [self.view.window center];
    [self.view.window setFrameOrigin:NSMakePoint(self.view.window.frame.origin.x, self.view.window.frame.origin.y)];
    self.mainView.frame = originalSizeRect;
    
    CGRect wRect = self.view.window.frame;
    CGRect cRect = self.view.window.contentView.frame;
    CGRect rect = CGRectMake(wRect.origin.x, wRect.origin.y-22, cRect.size.width, cRect.size.height);
    
    AppDelegate *appDelegate = (AppDelegate *)[NSApplication sharedApplication].delegate;
    [appDelegate.childWindow setFrame:rect display:YES animate:NO];
    appDelegate.childWindow.contentView.frame = CGRectMake(0, 0, cRect.size.width, cRect.size.height);
    [appDelegate.childWindow setFrameOrigin:NSMakePoint(self.view.window.frame.origin.x, self.view.window.frame.origin.y)];
    
    if (LarkMeetingManager.is4ShareScreen && !LarkMeetingManager.isSwitchVideoView)
    {
        self.meetingViewBuilder.screenShareMessageTextField.frame = CGRectMake(0, (kVideoHeight - 20)/2, kVideoWidth, 20);
        self.meetingViewBuilder.screenShareMessageTextField.font = [NSFont systemFontOfSize:16.0];
    }
    
    self.meetingViewBuilder.whiteBoardWebView.frame = CGRectMake(0, 0, kVideoWidth, kVideoHeight);
    [[self.meetingViewBuilder.whiteBoardWebView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.meetingViewBuilder.whiteBoardWebView.mainFrameURL]]];

    [self.meetingViewBuilder reloadMeetingViewToOriginalSize];
    [self.meetingViewBuilder.switchPageViewControl reloadCellInPageView];
    
    CGRect originalVideoRect = CGRectMake(0, 0, kVideoWidth, kVideoHeight);
    if (LarkMeetingManager.isSwitchVideoView)
    {
        NSView *remoteVideoView = [self.rongRTCEngine changeRemoteVideoViewFrame:originalVideoRect withUserID:self.selectedViewModel.userID withDisplayType:RongRTC_VideoViewDisplay_CompleteView];
        
        if (self.selectedViewModel.avType == RongRTC_User_Only_Audio || self.selectedViewModel.avType == RongRTC_User_Audio_Video_None)
        {
            self.selectedViewModel.micImageView.frame = CGRectMake((kVideoWidth-kCellSize)/2, (kVideoHeight-kCellSize)/2, self.selectedViewModel.micImageView.frame.size.width, self.selectedViewModel.micImageView.frame.size.height);
            [remoteVideoView addSubview:self.selectedViewModel.micImageView];
        }
        
        [appDelegate.childWindow.contentView addSubview:remoteVideoView];
    }
    else
    {
        if (LarkMeetingManager.observerIndex == RongRTC_User_Observer)
        {
            self.localVideoViewModel.cellVideoView = [self.rongRTCEngine changeRemoteVideoViewFrame:originalVideoRect withUserID:self.localVideoViewModel.userID withDisplayType:RongRTC_VideoViewDisplay_CompleteView];
        }
        else
        {
            self.localVideoViewModel.cellVideoView = [self.rongRTCEngine changeLocalVideoViewFrame:originalVideoRect withDisplayType:RongRTC_VideoViewDisplay_CompleteView];
        }
        
        if (self.localVideoViewModel.avType == RongRTC_User_Only_Audio || self.localVideoViewModel.avType == RongRTC_User_Audio_Video_None)
        {
            self.localVideoViewModel.micImageView.frame = CGRectMake((kVideoWidth-kCellSize)/2, (kVideoHeight-kCellSize)/2, self.localVideoViewModel.micImageView.frame.size.width, self.localVideoViewModel.micImageView.frame.size.height);
            [self.localVideoViewModel.cellVideoView addSubview:self.localVideoViewModel.micImageView];
        }
        
        [appDelegate.childWindow.contentView addSubview:self.localVideoViewModel.cellVideoView];
    }
}

#pragma mark - 窗口关闭
- (void)meetingWindowClosed
{
    [self.rongRTCEngine leaveChannel];
}

#pragma mark - 更新通话时间
- (void)updateTalkTimeLabel
{
    self.duration++;
    NSUInteger hour = self.duration / 3600;
    NSUInteger minutes = (self.duration - 3600 * hour) / 60;
    NSUInteger seconds = (self.duration - 3600 * hour - 60 * minutes) % 60;
    
    if (hour > 0)
        self.meetingViewBuilder.durationTimeTextField.stringValue = [NSString stringWithFormat:@"%01ld:%02ld:%02ld", (unsigned long)hour, (unsigned long)minutes, (unsigned long)seconds];
    else
        self.meetingViewBuilder.durationTimeTextField.stringValue = [NSString stringWithFormat:@"%02ld:%02ld", (unsigned long)minutes, (unsigned long)seconds];
}

#pragma mark - 规范信息
- (void)dataInfoButtonPressed
{
    //规范信息
    LarkMeetingManager.isDataInfoOpen = !LarkMeetingManager.isDataInfoOpen;
    if (LarkMeetingManager.isDataInfoOpen)
        [self.meetingViewBuilder.avInfoPanel makeKeyAndOrderFront:nil];
    else
    {
        [self.meetingViewBuilder.avInfoPanel orderOut:nil];
        [self.view.window orderFront:nil];
    }
}

#pragma mark - 切换分辨率
- (void)exchangeVideoSizeButtonPressed
{
    NSArray *videoSizeArray = @[@(RongRTC_VideoProfile_1920_1080P), @(RongRTC_VideoProfile_1280_720P), @(RongRTC_VideoProfile_720_480P), @(RongRTC_VideoProfile_640_480P), @(RongRTC_VideoProfile_640_360P), @(RongRTC_VideoProfile_480_360P), @(RongRTC_VideoProfile_320_240P), @(RongRTC_VideoProfile_256_144P)];
    NSInteger initSelectedIndex = [videoSizeArray indexOfObject:self.paraDic[kVideoProfile]];
    
    if (videoSizeSelectedIndex == -1)
        videoSizeSelectedIndex = initSelectedIndex + 1;
    else if (videoSizeSelectedIndex < [videoSizeArray count] - 1)
        videoSizeSelectedIndex++;
    else
        videoSizeSelectedIndex = initSelectedIndex;
    
    [self.rongRTCEngine changeVideoSize:[videoSizeArray[videoSizeSelectedIndex] integerValue]];
}

- (void)restoreCloseCameraState
{
    if (LarkMeetingManager.isCloseCamera)
    {
        LarkMeetingManager.isCloseCamera = !LarkMeetingManager.isCloseCamera;
        [self.rongRTCEngine closeLocalVideo:LarkMeetingManager.isCloseCamera];
        
        [self switchLeftMVCollectionViewItem:6 withLabelColor:[NSColor blackColor] withImageName:@"MeetingMenu6CameraGray"];
        self.localVideoViewModel.avType = RongRTC_User_Audio_Video;
        [self.localVideoViewModel.micImageView removeFromSuperview];
    }
}

- (void)restoreMuteState
{
    if (LarkMeetingManager.is7Mute)
    {
        LarkMeetingManager.is7Mute = !LarkMeetingManager.is7Mute;
        [self.rongRTCEngine muteMicrophone:LarkMeetingManager.is7Mute];
        
        if (LarkMeetingManager.is7Mute)
            [self switchLeftMVCollectionViewItem:7 withLabelColor:kThemeColor withImageName:@"MeetingMenu7MuteBlue"];
        else
            [self switchLeftMVCollectionViewItem:7 withLabelColor:[NSColor blackColor] withImageName:@"MeetingMenu7MuteGray"];
    }
}

- (void)reminderUserDeviceStatus
{
    if (LarkMeetingManager.observerIndex == RongRTC_User_Normal || LarkMeetingManager.observerIndex == RongRTC_User_Host)
    {
        static dispatch_once_t once_dispatch;
        dispatch_once(&once_dispatch, ^{
            NSArray *deviceArray = [AVCaptureDevice devices];
            if ([deviceArray count] < 2)
                [self showMessageAlertSingle:NSLocalizedString(@"meeting_msg_13", nil) title:NSLocalizedString(@"meeting_msg_14", nil)];
        });
    }
}

@end
